var util = require('../../utils/util.js')
var app = getApp()
var notificationCenter = require('../../utils/WxNotificationCenter')

Page({
    memberId: '',
    orderId: '',
    totalPrice: 0,
    hasChangeAddress: false,
    data: {
        havaDefaultAddress: false,
        item: {},
        addressData: {},
        phoneNumber: '',
        address: '',
        clientName: '',
        productInfo: {},
        postage: 0,
        time: '',
        price: 0,
        // provingBean:{},
        hongbaoList: {
          discount: 0,
          hongbaotype: 0,
          id: 0,}
    },
    onLoad: function (params) {
        var _this = this
        let mohuanUser = app.globalData.mohuanUser
        let memberId = mohuanUser.memberId
        // let memberId = '8a10a439520b1cd401520b511a4000cd'
        this.memberId = memberId
        this.orderId = params.orderId
      //先将mydata的缓存数据置为0
        wx.setStorage({
          key: "mydata",
          data: {
            discount: 0,
            hongbaotype: 0,
            id: 0,
          },
        })
       util.request(`/c2mwebservice/api/v1/members/${memberId}/addresses`, function (res) {
         console.log('获取收货地址' + res)
            // let data = res.returnData.currentList[0]
            let datas = res.returnData.currentList
            // console.log('获取收货地址列表'+ datas)
            if (datas.length != 0 ) {
                let data = datas.filter(function (obj) {
                    if (obj.isDefault) {
                        return true;
                    }
                })[0];
                if (!data) {
                    data = res.returnData.currentList[0]
                }
                _this.setData({
                    phoneNumber: data.phoneNo,
                    address: `${data.city}${data.suburb}${data.detail}`,
                    clientName: data.receiver,
                    addressData: data,
                    havaDefaultAddress: true,
                })
            } else {
                _this.setData({
                    havaDefaultAddress: false,
                    addressData: {},
                })
            }
            // if (data) {
            //     let phoneNumber = data.phoneNo
            //     let clientName = data.receiver
            //     let address = `${data.city}${data.suburb}${data.detail}`
            //     _this.setData({
            //         phoneNumber: phoneNumber,
            //         address: address,
            //         clientName: clientName,
            //         addressData: data,
            //         havaDefaultAddress: true
            //     })
            // } else {
            //     _this.setData({
            //         havaDefaultAddress: false,
            //         addressData: {}
            //     })
            // }

        }, function (error) {
            wx.showToast({
                title: '加载失败，请稍后再试',
            })
        })


        wx.getStorage({
            key: 'productInfo',
            success: function (res) {
                let product = {}
                if (res.data.suit) {
                    product.goodsName = res.data.suit.suitNameCn
                    product.materialName = res.data.goods[0].customization.material.materialName
                    product.size = `上衣：${res.data.goods[0].size.size} 裤子：${res.data.goods[1].size.size}`
                    product.count = res.data.suit.suitCount
                    product.price = res.data.suit.suitPrice
                    product.goodsImg = params.productImage
                } else {
                    product.goodsName = res.data.goods[0].goodsName
                    if (res.data.goods[0].customization.material) {
                        product.materialName = res.data.goods[0].customization.material.materialName
                    } else {
                        product.materialName = '默认面料'
                    }
                    product.size = `尺码:${res.data.goods[0].size.size}`
                    product.count = res.data.goods[0].count
                    product.price = res.data.goods[0].price
                    product.goodsImg = params.productImage
                }
                _this.setData({
                    item: product,
                    productInfo: res.data,
                })

                // 套装
                if (res.data.suit) {
                    params.totalPrice = res.data.suit.suitPrice
                } else {
                    params.totalPrice = res.data.goods[0].price
                }
                _this.totalPrice = params.totalPrice

                let timeParams = {}
                for (let index = 0; index < res.data.goods.length; index++) {
                    timeParams[res.data.goods[index].customization.categoryName] = res.data.goods[index].count
                }

                _this._loadFreight(function (res) {
                    let freight = 0
                    if (res.length > 0) {
                        for (let i = 0; i < res.length; i++) {
                            if (res[i].amountRange > _this.totalPrice) {
                                freight = res[i].postage
                                break;
                            }
                        }
                    }
                    let p = parseFloat(_this.totalPrice) * parseFloat(product.count) + parseFloat(freight)
                    _this.setData({
                        postage: freight,
                        price: p
                    })
                }, function (error) { })

                _this._loadPredictTime(timeParams, function (res) {
                    _this.setData({
                        time: res
                    })
                }, function (error) { })
            },
            fail: function () {
            },
            complete: function () {
                wx.removeStorage({
                    key: 'productInfo',
                })
            }
        })
       
    },
onHide:function(){
  /**
         * 将红包列表数据置为0
         */
  wx.setStorage({
    key: "mydata",
    data: {
      discount: 0,
      hongbaotype: 0,
      id: 0,
      }
  })
},
/**
 * 每次页面重新显示都会调用此方法，hongbaoList会有两套值，全部为0或者全部有值。onload和onHide方法会把hongbaolist数据全部置为0
 */
    onShow: function () {
        let _this = this
        //接收来自红包列表页面传递的值
        wx.getStorage({
          //获取数据的key
          key: 'mydata',
          success: function (res) {
            console.log("接收到来自红包页面传递过来的值"+res)
            _this.setData({
              //页面数据存储
              hongbaoList: res.data
            })
          },
          /**
           * 失败会调用
           */
          fail: function (res) {
            console.log(res)
          }
        })
      
        if (!this.data.havaDefaultAddress || this.hasChangeAddress) {
            wx.getStorage({
                key: 'Address',
                success: function (data) {
                    let phoneNumber = data.data.phoneNo
                    let clientName = data.data.receiver
                    let address = `${data.data.city}${data.data.suburb}${data.data.detail}`
                    _this.setData({
                        phoneNumber: phoneNumber,
                        address: address,
                        clientName: clientName,
                        addressData: data.data,
                        havaDefaultAddress: true
                    })
                    _this.hasChangeAddress = false
                },
                fail: function () {
                },
                complete: function () {
                    wx.removeStorage({
                        key: 'Address'
                    })
                }
            })
        }
    },

    //付款按钮点击
    orderPay: function () {
        this._orderSure(function (res) {
        }, function (error) {
            wx.showToast({
                title: res.data.returnMsg,
                duration: 2000
            })
        })
    },
    //验证成功执行 _orderPay方法
    _orderSure: function (success, faliure) {
        let params = {}
        // 套装
        // if (this.data.productInfo.goods.length>1) {
        //     params.totalPrice = this.data.productInfo.suit.suitPrice
        // } else {
        //     params.totalPrice = ''
        // }
        // this.totalPrice = params.totalPrice
        var discount = this.data.hongbaoList.discount;
        if(discount!=0){
          params.totalPrice = this.data.price-discount,
          params.payInfoItem = [
            {
              "postage": 0,
              "storeTotalPrice": this.data.price,
              "payment": {
                "payment": this.data.price-discount
              },
              "discount": [
                {
                  "discountType": 20,
                  "id": this.data.hongbaoList.id,
                  "value": this.data.hongbaoList.discount
                }
              ],
              "invoice": {
                "address": "",
                "accountBank": "",
                "accountNo": "",
                "invoiceType": "2",
                "taxerName": "个人",
                "companyName": "",
                "phoneNo": "",
                "taxerIdNo": ""
              },
              "price": this.data.price,
              "separateFlag": "0"
            }
          ]
        }
        else{
        params.totalPrice = this.data.price
        params.payInfoItem = [
            {
                "postage": 0,
                "storeTotalPrice": this.data.price,
                "payment": {
                    "payment": this.data.price
                },
                "discount": [],
                "invoice": {
                    "address": "",
                    "accountBank": "",
                    "accountNo": "",
                    "invoiceType": "2",
                    "taxerName": "个人",
                    "companyName": "",
                    "phoneNo": "",
                    "taxerIdNo": ""
                },
                "price": this.data.price,
                "separateFlag": "0"
            }
        ]
    }
        params.orderId = this.orderId
        params.payment = {
            "payment": this.data.price
        }
        if (!this.data.addressData.phoneNo) {
            wx.showToast({
                title: '请填写地址',
            })
            return
        }
        params.address = {
            "postCode": this.data.addressData.postal,
            "suburb": this.data.addressData.suburb,
            "city": this.data.addressData.city,
            "userName": this.data.addressData.receiver,
            "addressDetail": this.data.addressData.detail,
            "userTel": this.data.addressData.phoneNo,
            "province": this.data.addressData.province
        }
        wx.showToast({
            title: '加载中',
            icon: 'loading',
            duration: 10000
        })
        let _this = this
        console.log("params为"+JSON.stringify(params));
        util.postRequest(`/c2mwebservice/api/v2/${this.memberId}/shoppingCarts/trade`, params, function (res) {
          
          console.log("未调用支付接口之前，请求成功的res"+JSON.stringify(res))
            _this._orderPay(params.totalPrice, function (res) {
            }, function (error) {
                wx.showToast({
                    title: res.data.returnMsg,
                    duration: 2000
                })
            })
        }, function (res) {
            wx.showToast({
                title: res.data.returnMsg,
                duration: 2000
            })
        })
     
    },
 
    //付款
    _orderPay: function (totalPrice, success, failure) {
    //  debugger;
      console.log('--获取openID--'+app.globalData)
      var discount = this.data.hongbaoList.discount;
        var orderId = this.orderId + "";
        var openid = app.globalData.openId;
        // var discount=this.data.hongbaoList.discount;
        // var price=this.data.price-discount;
      
        var params = {
            "payMethod": "07",
            "balance": 0,
            "totalPrice": this.data.price-discount,
            "openid": openid, //
            "orderId": [orderId]
        }
      console.log('调用支付接口参数')
        console.log(params)
        //后台报500，可能是因为orderId/openid/memberId 不存在；在正式服务器找不到

        //04 安卓app
        // let params = {
        //     "orderId": [
        //         this.orderId
        //     ],
        //     "payMethod": '04',
        //     "balance": 0,
        //     "totalPrice": totalPrice,
        //     "openid": app.globalData.userInfo.openId
        // }



// debugger
        //获取支付参数   调用微信支付
        //c2mwebservice/api/v2/tradeOrder/1/orderPay
      console.log(params)
      console.log('==支付参数====')
        util.postRequest(`/c2mwebservice/api/v2/tradeOrder/${this.memberId}/orderPay`, params, function (res) {
            var datas = res;
            console.log("datas=" + JSON.stringify(res) );
            var packageDate = "prepay_id=" + datas.returnData.widgetCode.prepayid;
            wx.requestPayment({
                'appId': datas.returnData.widgetCode.appId,//小程序ID
                'timeStamp': datas.returnData.widgetCode.timeStamp,//时间戳
                'nonceStr': datas.returnData.widgetCode.nonceStr,//随机字符串，不长于32位
                'package': datas.returnData.widgetCode.package,//数据包
                'signType': 'MD5',//签名方式
                'paySign': datas.returnData.widgetCode.paySign,
                success: function (res) {
                    //如果成功，返回errMsg
                    // errMsg  :  "requestPayment:ok"
                    console.log("****************chenggong*******"+res)
                    console.log("=======================>支付成功")
                    wx.navigateTo({
                        url: `../OrderList/OrderList?status=0`,
                        success: function (res) {
                        },
                        fail: function () {
                        },
                        complete: function () {
                        }
                    })
                },
                fail: function (res) {
                  console.log("********************shibai***" + res)
                    wx.showToast({
                        title: res.data.returnMsg,
                        duration: 2000
                    })
                    console.log("=======================>支付失败")
                },
                complete: function (res) {
                    wx.showToast({
                        title: res.data.returnMsg,
                        duration: 2000
                    })
                    console.log("=======================>支付回调")
                }
            })
        }, function (error) {
            wx.showToast({
                title: res.data.returnMsg,
                duration: 2000
            })
        })
    },
    //加载尺码
    _loadFreight: function (success, faliure) {
        util.request(`/c2mwebservice/api/v2/public/postage/`, function (res) {
            if (res && res.returnData.length > 0) {
                let info = res.returnData.map(function (data) {
                    let bounds = data.amountRange.split("-")

                    let newData = {}
                    newData.postage = data.postage
                    newData.amountRange = parseFloat(bounds[1])
                    return newData
                })
                if (success) {
                    success(info)
                }
            } else {
                if (success) {
                    success([])
                }
            }

        }, function (error) { if (faliure) { faliure(error) } });
    },

    //预计时间
    _loadPredictTime: function (params, success, failure) {
        util.postRequest(`/c2mwebservice/api/v2/trade/${this.memberId}/expectedDeliveryDate`, params, function (res) {
            if (success) {
                success(res.returnData)
            }
        }, function (error) {
            console.log(error)
        })
    },
    //单击改变收货地址
    changeAddress: function () {
        this.hasChangeAddress = true
        notificationCenter.addNotification('changeAddress', this._changeAddress, this);
        wx.navigateTo({
            url: '../address/chooseAddressList',
        })
    },

    //单击改变收货地址
    _changeAddress: function (obj) {
        var _this = this;
        notificationCenter.removeNotification('changeAddress', this)
        _this.setData({
            phoneNumber: obj.phoneNo,
            address: `${obj.city}${obj.suburb}${obj.detail}`,
            clientName: obj.receiver,
            addressData: obj,
        })
    },

    //增加地址
    addAddress: function () {
        wx.navigateTo({
            url: '../address/addressEdit',
            success: function (res) {
                // success
            },
            fail: function () {
                // fail
            },
            complete: function () {
                // complete
            }
        })
    },
    onUnload: function (e) {
      /**
       * 清除红包列表数据
       */
      wx.setStorage({
        key: "mydata",
        data: {
          discount: 0,
          hongbaotype: 0,
          id: 0,
        },
      })
        // notificationCenter.removeNotification('changeAddress', this)
    },

//点击选择红包触发的事件，传递此商品的价格、品类和当前时间到红包页面进行验证
    clickhongbao:function(e){
      // let that =this;
      // that.data.provingBean.categoryId = this.data.productInfo.goods[0].customization.categoryId;
      // that.data.provingBean.price=this.data.price;
      // var nowDate = new Date().getTime(); 
      // that.data.provingBean.time=nowDate;
      // //provingBean组装完成
      // console.log("组装完成的bean为" + JSON.stringify(that.data.provingBean));
      // e.target.dataset.provingBean = provingBean;
      //传递商品价格和品类ID到红包列表页面
      wx.navigateTo({
        url: '../HongBao/HongBao?price=' + this.data.price + "&categoryId=" + this.data.productInfo.goods[0].customization.categoryId,
      })
      // console.log("品类为" + this.data.productInfo.goods[0].customization.categoryId);

      // console.log("*************" + JSON.stringify(this.data.productInfo));
      // //1505986324852  1506126209387
      // let now=new Date(parseInt(("/Date(" + nowDate + ")/").substr(6, 13))).toLocaleDateString()
      // console.log(now );
      // var nowtime=new Date(now);
      // var fromtime=new Date("2017/8/2");
      // console.log("当前时间大于红包时间"+nowtime<fromtime);
    }
});